<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>制作表情包</title>
    <style>
        #canvas {
            border: 2px solid #999;
        }
    </style>
</head>

<body>
    <canvas id="canvas" width="330" height="330"></canvas>


    <script>
        var canvas = document.getElementById('canvas');
        var ctx = canvas.getContext('2d');

        ctx.font = "14px arial";
        ctx.fillStyle="#000"

        var text = "这是一个令人欲罢不能的射击游戏，使用 ← 和 → 操作你的飞机，使用空格（space）进行射击。一起来消灭宇宙怪兽吧！"
        var subIndex = 0
        var lineWidth = 0
        var width = 330
        var textArr = []
        var lineHeight = 20

        for (let index = 0; index < text.length; index++) {
            let element = text[index];
            lineWidth += (ctx.measureText(element).width*1.17)

            //console.log(ctx.measureText(element))

            if (lineWidth >= 330) {

                var subText = text.slice(subIndex, index)
                subIndex = index
                lineWidth = 0

                //console.log(subText)
                textArr.push({
                    subText,
                    lineHeight
                })

                lineHeight +=20
            }

        }

        for (var i = 0; i < textArr.length; i++) {
            let element = textArr[i];
            console.log(element)
            ctx.fillText(element.subText, 0, element.lineHeight);
        }

    </script>
</body>

</html>